//
//  CreateAdvertisingFormSwiftViewController.swift
//  iModern
//
//  Created by 立雄 王 on 15/6/26.
//  Copyright (c) 2015年 com.starlooking. All rights reserved.
//

import UIKit
import XLForm

class CreateAdvertisingFormViewController: FormViewController
{
    var attachments: NSMutableArray!
    // [[String:AnyObject]] key:descripiton,image
    var advertising        = NSMutableDictionary()
    var advertisingManager = AdvertisingManager()
    var attachmentManager = AttachmentManager()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.navigationItem.title = "添加商品"
        self.initBackButton()

        let image  = UIImage(named: "Save-Small.png")
        let button = UIBarButtonItem(image: image?.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "createAdvertising:")
        self.navigationItem.rightBarButtonItem = button

        self.initializeForm()

        // Do any additional setup after loading the view.
    }

    func initializeForm()
    {
        var form:    XLFormDescriptor
        var section: XLFormSectionDescriptor
        var row:     XLFormRowDescriptor

        form = XLFormDescriptor(title: " ")

        section = XLFormSectionDescriptor.formSectionWithTitle("")
        section.footerTitle = ""
        form.addFormSection(section)

        //        row = XLFormRowDescriptor(tag: "indexOfSaleTags", rowType: XLFormRowDescriptorTypeButton, title: "icon     分类")
        //        row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.Left.rawValue
        //        row.action.formSelector = "buttonLeftAlignedRow:"
        //        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "indexOfSaleTags", rowType: XLFormRowDescriptorTypeSelectorPush, title: "icon     选择分类")
        let a = ["服装", "珠宝", "鞋子", "箱包", "绘画", "皮艺", "纸艺", "陶艺", "女红", "纹身", "玩具", "乐器", "茶艺", "陶艺", "文玩", "绘画", "家具", "装修", "园艺", "女红", "修理", "美食", "布艺", "美妆", "健康", "茶艺", "酒水", "纹身", "电子科技"]
        row.selectorOptions = a
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "summary", rowType: XLFormRowDescriptorTypeText, title: "商品名称:")
        row.required = true
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "message", rowType: XLFormRowDescriptorTypeText, title: "商品描述:")
        row.required = true
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "price", rowType: XLFormRowDescriptorTypeNumber, title: "宝贝单价:")
        row.required = true
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "amountOfStocks", rowType: XLFormRowDescriptorTypeNumber, title: "商品库存:")
        row.required = true
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "preset", rowType: XLFormRowDescriptorTypeSelectorPush, title: "预定时间:")
        let preset = ["当日可预定", "需提前一天预定", "需提前两天预定", "需提前三天预定", "需提前一周预定"]
        row.selectorOptions = preset
        section.addFormRow(row)

        section = XLFormSectionDescriptor.formSectionWithTitle("更多介绍")
        form.addFormSection(section)

        row = XLFormRowDescriptor(tag: "pmi", rowType: XLFormRowDescriptorTypeText, title: "制作流程:")
        row.required = true
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "pom", rowType: XLFormRowDescriptorTypeText, title: "原料配方:")
        row.required = true
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "story", rowType: XLFormRowDescriptorTypeText, title: "特色说明:")
        row.required = true
        section.addFormRow(row)

        self.form = form
    }

    func buttonLeftAlignedRow(sender: XLFormRowDescriptor)
    {
        let indexOfSaleTagsViewController = IndexOfSaleTagsViewController()
        indexOfSaleTagsViewController.adver = self.advertising
        self.pushViewController(indexOfSaleTagsViewController)
    }

    @IBAction func createAdvertising(sender: AnyObject)
    {
        let attachment = attachments[0] as! NSMutableDictionary

        let indexOfSaleTags = self.formValues()["indexOfSaleTags"] as? String
        if indexOfSaleTags == nil
        {
            self.alertWarningMessage("请填写分类")
            return
        }

        let summary = self.formValues()["summary"] as? String
        let filter = SensitiveWordsFilter()
        let valid: Bool =  filter.validating(summary)
        if !valid
        {
            self.alertWarningMessage("你填写的商品名称可能包含敏感内容.")
            return
        }
        if summary == nil
        {
            self.alertWarningMessage("请填写商品名称")
            return
        }

        let message = self.formValues()["message"] as? String
        let valids: Bool = filter.validating(message)
        if !valids
        {
            self.alertWarningMessage("你填写的商品描述可能包含敏感内容.")
            return
        }
        if message == nil
        {
            self.alertWarningMessage("请填写商品描述")
            return
        }
//        else
//        {
//            self.advertising["message"] = self.formValues()["message"]
//        }

        let price = self.formValues()["price"] as? Int
        if price == nil
        {
            self.alertWarningMessage("请填写价格")
            return
        }

        let prices = self.formValues()["price"] as? Int
        if prices < 0 || prices > 10000
        {
            self.alertWarningMessage("价格应该在0至10000元之间")
            return
        }

        let amountOfStocks = self.formValues()["amountOfStocks"] as? Int
        if amountOfStocks == nil
        {
            self.alertWarningMessage("请填宝贝数量")
            return
        }

        let preset = self.formValues()["preset"] as? String
        if preset == nil
        {
            self.alertWarningMessage("请填预定方式")
            return
        }

        let pmi = self.formValues()["pmi"] as? String

        let valid2: Bool = filter.validating(pmi)
        if !valid2
        {
            self.alertWarningMessage("你填写的制作流程可能包含敏感内容.")
            return
        }
        if pmi == nil
        {
            self.alertWarningMessage("请填制作流程")
            return
        }

        let pom = self.formValues()["pom"] as? String
        let valid3: Bool = filter.validating(pom)
        if !valid3
        {
            self.alertWarningMessage("你填写的原料配方可能包含敏感内容.")
            return
        }
        if pom == nil
        {
            self.alertWarningMessage("请填原料配方")
            return
        }

        let story = self.formValues()["story"] as? String
        let valid4: Bool = filter.validating(pmi)
        if !valid4
        {
            self.alertWarningMessage("你填写的特色说明可能包含敏感内容.")
            return
        }
        if story == nil
        {
            self.alertWarningMessage("请填特色说明")
            return
        }

        let image = attachment["image"] as? UIImage

        self.advertising["image"] = image

        attachments.removeObjectAtIndex(0)

        self.advertising["images"] = attachments


        self.advertising["indexOfSaleTags"] = self.formValues()["indexOfSaleTags"]
        self.advertising["summary"] = self.formValues()["summary"]
        self.advertising["message"] = self.formValues()["message"]
        self.advertising["price"] = self.formValues()["price"]
        self.advertising["amountOfStocks"] = self.formValues()["amountOfStocks"]
        self.advertising["preset"] = self.formValues()["preset"]
        self.advertising["pmi"] = self.formValues()["pmi"]
        self.advertising["pom"] = self.formValues()["pom"]
        self.advertising["story"] = self.formValues()["story"]
        self.advertising["type"] = "Advertising";

        let rs = advertisingManager.createAdvertising(self.advertising as [NSObject:AnyObject])

        if rs == nil
        {
            self.alertNetworkConnectionException()
            return
        }

        if rs!.hasErrors()
        {
            if rs?.errorCode == 3020
            {
                self.alertUserStatusException()
            }
            else
            {
                self.alertErrorMessage(rs!.errorMessage)
            }
        }
        /*
        else
        {
            var imageobj :UIImage
            var desc:String
            var attachmentobj :NSMutableDictionary
            var advertisingobj = rs.toMutableDictionary() as NSMutableDictionary
            var i :Int
            var articleid = advertisingobj["id"] as! Int
            for(i=0;i<attachments.count;i++){
                attachmentobj = attachments[i] as! NSMutableDictionary
                imageobj = attachmentobj["image"] as! UIImage
                desc = attachmentobj["summary"] as! String
                attachmentManager.uploadImage(String(articleid), image: imageobj,desc:desc)
            }
        }
        */
        self.view.endEditing(true)
        self.navigationController?.popToRootViewControllerAnimated(true)

    }

    override func formRowDescriptorValueHasChanged(formRow: XLFormRowDescriptor!, oldValue: AnyObject!, newValue: AnyObject!)
    {
        if formRow.tag == "pickup"
        {
            if formRow.value?.valueData() as? Bool == true
            {
                self.advertising["pickup"] = self.formValues()["pickup"]
            }
            else
            {
                self.advertising["cityExpress"] = self.formValues()["pickup"]
            }
        }

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */

}
